package com.xzz.listnode;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @author: hhz
 * @create: 2021-12-17 17:40
 * 21. 合并两个有序链表
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 **/
public class MergeTwoLists {
    static class ListNode {
        int val;
        ListNode next;
        ListNode() {
        }
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public static void main(String[] args) {
        ListNode list1 = new ListNode(1,new ListNode(2,new ListNode(4)));
        ListNode list2 = new ListNode(1,new ListNode(3,new ListNode(4)));
//        ListNode listNode = mergeTwoLists(list1, list2);
        ListNode listNode = mergeTwoLists2(list1, list2);
        while (null != listNode){
            System.out.print(listNode.val);
            if(listNode.next!=null){
                System.out.print(",");
            }
            listNode = listNode.next;
        }
    }
    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        PriorityQueue<ListNode> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o.val));
        while (null != list1){
            queue.offer(list1);
            list1 = list1.next;
        }
        while (null != list2){
            queue.offer(list2);
            list2 = list2.next;
        }
        ListNode head = new ListNode(0);
        ListNode tail = head;
        while (!queue.isEmpty()) {
            ListNode poll = queue.poll();
            poll.next = null;
            tail.next = poll;
            tail = tail.next;
        }
        return head.next;
    }
    public static ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
        ListNode head = new ListNode(0);
        ListNode tail = head;
        ListNode p1 = list1;
        ListNode p2 = list2;
        while(p1 !=null && p2!=null){
            if(p1.val>p2.val){
                tail.next = p2;
                p2 = p2.next;
            }else {
                tail.next = p1;
                p1 = p1.next;
            }
            tail = tail.next;
        }
        if(p1!=null){
            tail.next = p1;
        }
        if(p2!=null){
            tail.next = p2;
        }
        return head.next;
    }
}
